package com.platform.qujia.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.platform.qujia.constantEnum.CouponSwitchConstant;
import com.platform.qujia.dao.*;
import com.platform.qujia.enums.CarWashEnum;
import com.platform.qujia.enums.CouponPushRuleEnum;
import com.platform.qujia.enums.WxTemplateEnum;
import com.platform.qujia.pojo.*;
import com.platform.qujia.pojo.dto.CouponPaymetDto;
import com.platform.qujia.pojo.dto.CouponUserDto;
import com.platform.qujia.pojo.dto.carWashPaymentDto;
import com.platform.qujia.pojo.dto.newCarWashPaymetDto;
import com.platform.qujia.pojo.vo.CouponPushMessageRuleVo;
import com.platform.qujia.pojo.vo.CouponUserVo;
import com.platform.qujia.service.*;
import com.platform.qujia.utils.CodeMsg;
import com.platform.qujia.utils.CryptUtil;
import com.platform.qujia.utils.ResultData;
import com.platform.qujia.utils.exception.CustomException;
import com.platform.qujia.utils.weixinapp.WxPushUtil;
import com.platform.qujia.utils.weixinapp.WxTemplateData;
import com.platform.qujia.utils.weixinapp.WxTemplateMsg;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service("couponService")
@Slf4j
public class CouponServiceImpl implements CouponService {
    @Resource
    private CouponMapper couponMapper;
    @Resource
    private AppUserInfoMapper appUserInfoMapper;
    @Resource
    private GradeMapper gradeMapper;
    @Resource
    private AppUserSuperDetailService appUserSuperDetailService;
    @Resource
    private PayOrderMapper payOrderMapper;
    @Resource
    private EnterpriseMapper enterpriseMapper;
    @Resource
    private WxPushUtil wxPushUtil;

    @Value("${qujia.domainName}")
    private String domainName;

    @Resource
    private CouponService couponService;

    @Resource
    private PosMachineService posMachineService;

    @Resource
    private PayOrderService payOrderService;

    @Resource
    private EnterpriseService enterpriseService;

    @Resource
    private AppUserInfoService appUserInfoService;

    @Resource
    private StationMapper stationMapper;

    @Resource
    private CouponInfoMapper couponInfoMapper;

    @Resource
    private ElectronicMembershipCardService electronicMembershipCardService;

    @Resource
    private StaOilGunMapper staOilGunMapper;

    @Resource
    private CouponWriteOffRecordsMapper couponWriteOffRecordsMapper;

    @Autowired
    private CustomerCardSettingDetailService customerCardSettingDetailService;

    @Resource
    private PresentCouponUserRecordMapper presentCouponUserRecordMapper;
    @Autowired
    private IUserVirtualGradeRelService userVirtualGradeRelService;
    @Resource
    private RedisTemplate<String,String> redisTemplate;


    @Override
    public List<CouponUser> selectVerUserCouponList(CouponUser couponUser) {
        return couponMapper.selectVerUserCouponList(couponUser);
    }

    @Override
    public int selectCouUserSum(CouponUser couponUser) {
        return couponMapper.selectCouUserSum(couponUser);
    }

    /**
     * 统计优惠券数量
     * @param mobilePhone
     * @param enterpriseId
     * @return
     */
    public int setCoupnCount(String mobilePhone, Integer enterpriseId) {
        return couponMapper.setCoupnCount(mobilePhone, enterpriseId);
    }
    @Override
    public CouponIssue selectCouponIssueInfo(CouponIssue couponIssue) {
        return couponMapper.selectCouponIssueInfo(couponIssue);
    }

    @Override
    public int selectCouponUserGiveCountByToday(CouponUserGiveCount couponUserGiveCount) {
        return couponMapper.selectCouponUserGiveCountByToday(couponUserGiveCount);
    }

    @Override
    public int selectCouponUser(String couponIssueId, String mobilePhone) {
        return couponMapper.selectCouponUser(couponIssueId,mobilePhone);
    }

    @Override
    public List<CouponIssue> selectCouponListByCouponIssueId(Map<String, Object> param) {
        return couponMapper.selectCouponListByCouponIssueId(param);
    }

    // 根据活动 ID 查询对应的 issue_id 列表
    @Override
    public List<String> getIssueIdsByActivityId(String activityId) {
        return couponMapper.getIssueIdsByActivityId(activityId);
    }

    @Override
    public List<String> getIssueIdsandCouponByActivityId(String activityId) {
        return couponMapper.getIssueIdsandCouponByActivityId(activityId);
    }

    // 根据活动 ID 查询对应的 issue_id 列表
    @Override
    public List<String> getIssueIdsByActivityIdAndAmt(String activityId, BigDecimal receivedAmt) {
        // 获取满足条件的最大 threshold_amt 值
        BigDecimal thresholdAmt = couponMapper.getThresholdAmtByActivityIdAndAmt(activityId, receivedAmt);

        if (thresholdAmt != null) {
            // 根据最大 threshold_amt 值获取对应的 issue_id 列表
            List<String> issueIds = couponMapper.getIssueIdsByThresholdAmt(activityId, thresholdAmt);
            return issueIds;
        } else {
            // 如果 thresholdAmt 为 null，表示没有符合条件的数据
            return new ArrayList<>();
        }
    }

    @Override
    public Map<String, Object> getActivityAllByActivityId(String activityId) {
        return couponMapper.getActivityAllByActivityId(activityId);
    }

    @Override
    public String getAppUserGrowLevel(String mobilePhone, Long enterpriseId) {
        Map<String, Object> param = new HashMap<>();
        param.put("mobilePhone", mobilePhone);
        param.put("enterpriseId", enterpriseId);
        param.put("superName", "年卡");
        String grow = new String();
        String supergrow = couponMapper.getSuperGrow(param);
        if (supergrow!=null&&supergrow.equals("1")) {
            return "8";
        }
        param.put("superName", "季卡");
        supergrow = couponMapper.getSuperGrow(param);
        if (supergrow!=null&&supergrow.equals("1")) {
            return "7";
        }
        param.put("superName", "月卡");
        supergrow = couponMapper.getSuperGrow(param);
        if (supergrow!=null&&supergrow.equals("1")) {
            return "6";
        }
        UserVirtualGradeRel virtualGradeRel = userVirtualGradeRelService.queryUserVirtualGrade(enterpriseId, mobilePhone, LocalDateTime.now());
        if (virtualGradeRel != null) {
            return virtualGradeRel.getGradeCode();
        }
        grow = couponMapper.getGrow(param);
        return grow;
    }

    @Override
    public String checkisLabelUser(String mobilePhone, Long enterpriseId, String couponIssueId) {
        Map<String, Object> labelParam = new HashMap<>();
        labelParam.put("mobilePhone", mobilePhone);
        labelParam.put("enterpriseId", enterpriseId);
        labelParam.put("couponActivityId", couponIssueId);
//        标签
        String labelActivityIds = couponMapper.checkLabelCouponActivity(labelParam);
        if (labelActivityIds == null || labelActivityIds == "") {
//            不符合返回0
            return "0";
        } else {
            return "1";
        }
    }

    @Override
    public String checkCouponActivity(Integer enterpriseId, PayOrder payOrderInfo, Double amt) {
        BigDecimal receivedAmt;
        if (amt == 0.0 && !payOrderInfo.getPayType().equals("dzk")) {
            receivedAmt = BigDecimal.valueOf(payOrderInfo.getAmt());
        } else {
//            电子卡情况
            receivedAmt = BigDecimal.valueOf(amt);
        }
//        微信1支付宝2现金3银行卡4电子卡5实体卡6
        String payType = "1";
        if (payOrderInfo.getPayType().equals("dzk")) {
            payType = "5";
        } else if (payOrderInfo.getPayType().equals("zfb")) {
            payType = "2";
        } else {
            payType = "1";
        }

        Map<String, Object> labelParam = new HashMap<>();
        labelParam.put("mobilePhone", payOrderInfo.getCustomerPhone());
        labelParam.put("enterpriseId", Long.valueOf(enterpriseId));
//        标签
        String labelActivityIds = couponMapper.checkLabelCouponActivity(labelParam);
        List<String> activityIdList = new ArrayList<>();
        Set<String> uniqueActivityIdSet = new HashSet<>();
        if (labelActivityIds != null && labelActivityIds != "") {
            String[] uniqueActivityIds = labelActivityIds.split(",");
            for (String activityId : uniqueActivityIds) {
                activityIdList.add(activityId);
                uniqueActivityIdSet.add(activityId);
            }
        }

//        会员级别
        String userMemberLevel = couponService.getAppUserGrowLevel(payOrderInfo.getCustomerPhone(), Long.valueOf(enterpriseId));
        Map<String, Object> param = new HashMap<>();
        param.put("enterpriseId", enterpriseId);
        param.put("payType", payType);
        param.put("userMemberLevel", userMemberLevel);
        param.put("activityIds", uniqueActivityIdSet);
        if(payOrderInfo.getOilId()!=null){
            param.put("oilId", payOrderInfo.getOilId());
        }
        List<String> activityIds = new ArrayList<>();
        if (uniqueActivityIdSet.size() != 0) {
            activityIds = couponMapper.checkCouponActivityOnLabelAll(param);
            List<String>  activityIds2 = couponMapper.checkCouponActivityOnLabel(param);
            if(activityIds2!=null&&activityIds2.size()>0){
                activityIds.addAll(activityIds2);
            }
        }
        if (activityIds.size() == 0) {
            activityIds = couponMapper.checkCouponActivityAll(param);
            List<String>  activityIds2 = couponMapper.checkCouponActivity(param);
            if(activityIds2!=null&&activityIds2.size()>0){
                activityIds.addAll(activityIds2);
            }
        }
        if (activityIds != null && !activityIds.isEmpty()) {
            Map<String, Object> thresholdParam = new HashMap<>();
            thresholdParam.put("receivedAmt", receivedAmt);
            thresholdParam.put("activityIds", activityIds);
            String activityId = null;
            if(payOrderInfo.getAmtOrReceivable() == 1){
                activityId =   couponMapper.checkThresholdCouponActivityYingFu(thresholdParam);
            }else{
                activityId =   couponMapper.checkThresholdCouponActivity(thresholdParam);
            }
            return activityId;
        } else {
            return "0";
        }
    }



    @Override
    public int saveCouponUser(CouponUser couponUser) {
        return couponMapper.saveCouponUser(couponUser);
    }

    @Override
    public int saveBatchCouponUser(List<CouponUser> couponUsersList) {
        return couponMapper.saveBatchCouponUser(couponUsersList);
    }

    @Override
    public int updateBatchCouponTemplate(List<Integer> ids) {
        return couponMapper.updateBatchCouponTemplate(ids);
    }

    @Override
    public int updateCouponTemplate(CouponTemplate couponTemplate) {
        return couponMapper.updateCouponTemplate(couponTemplate);
    }

    @Override
    public int updateCouponUser(CouponUser couponUser) {
        return couponMapper.updateCouponUser(couponUser);
    }

    //    @Override
    public CouponUserGiveCount selectCouponUserGiveCount(CouponUserGiveCount couponUserGiveCount) {
        return couponMapper.selectCouponUserGiveCount(couponUserGiveCount);
    }

    @Override
    public int updateCouponUserGiveCount(CouponUserGiveCount couponUserGiveCount) {
        return couponMapper.updateCouponUserGiveCount(couponUserGiveCount);
    }

    @Override
    public int insertCouponUserGiveCount(CouponUserGiveCount couponUserGiveCount) {
        return couponMapper.insertCouponUserGiveCount(couponUserGiveCount);
    }

    @Override
    public int selectUserIssueGiveCount(CouponUserGiveCount couponUserGiveCount) {
        return couponMapper.selectUserIssueGiveCount(couponUserGiveCount);
    }
    /***
     * 查询最后一次领取的随机数
     * @param couponUser
     * @return
     */
    @Override
    public CouponUser selectUserIssueRedomMax(CouponUserGiveCount couponUser){
        return couponMapper.selectUserIssueRedomMax(couponUser);
    }

    @Override
    public List<CouponTemplate> selectCouponTemListByCouponUser(CouponUser couponUser) {
        return couponMapper.selectCouponTemListByCouponUser(couponUser);
    }

    @Override
    public List<CouponTemplate> selectCouponTemListByTemIds(CouponTemplate couponTemplate) {
        return couponMapper.selectCouponTemListByTemIds(couponTemplate);
    }

    @Override
    public CouponTemplate selectCouponTemInfoById(CouponTemplate couponTemplate) {
        return couponMapper.selectCouponTemInfoById(couponTemplate);
    }

    @Override
    public List<CouponUser> selectUserAllCoupons(CouponUser couponUser) {
        if(couponUser.getCouponIsUsed()!=null&&couponUser.getCouponIsUsed().equals("3")){
            if(couponUser.getVerificationTimeString()!=null){
                return     couponMapper.selectUserAllCouponsByVtime(couponUser);
            }
            return     couponMapper.selectUserAllCouponsByVtime(couponUser);
        }else{
             List<CouponUser> couponUsers=   couponMapper.selectUserAllCoupons(couponUser);
            for(CouponUser couponUserItem : couponUsers) {
                if(couponUserItem.getOils() == null || couponUserItem.getOils().isEmpty()) {
                    couponUserItem.setOils(couponUserItem.getNotOils());
                    couponUserItem.setIsOilType(1);
                }else{
                    couponUserItem.setIsOilType(0);
                }
            }
            return couponUsers;
        }
    }

    @Override
    public List<CouponUser> selectUsedCoupons(CouponUser couponUser) {
        return couponMapper.selectUsedCoupons(couponUser);
    }

    /**
     * 计算用户可用优惠券使用后应付的金额
     * @param mobilePhone
     * @param enterpriseId
     * @param amt
     * @return
     */
    @Override
    public List<CouponUser> calCouponAmt(String mobilePhone, Integer enterpriseId, BigDecimal amt) {
        List<CouponUser> resultCouTemList = new ArrayList<>();
        List<CouponUser> couponUserList = couponMapper.selectUserAllCoupons(CouponUser.builder()
                .couTypeParam("12") //优惠券类型 1 现金 2 折扣
                .couponIsUsed("0")  //未使用
                .mobilePhone(mobilePhone)
                .enterpriseId(enterpriseId).build());
        if (null != couponUserList && couponUserList.size() > 0) {
            for (CouponUser couponUser : couponUserList) {
                if (null != couponUser.getCouponTemplateInfo()) {
                    BigDecimal newAmt = amt;
                    String couponType = couponUser.getCouponTemplateInfo().getCouponType();
                    //优惠券类型
                    switch (couponType) {
                        case "1":
                            newAmt = amt.subtract(couponUser.getCouponTemplateInfo().getCouponAmt());
                            if (newAmt.compareTo(BigDecimal.ZERO) == 0 || newAmt.compareTo(BigDecimal.ZERO) == -1)
                                newAmt = new BigDecimal("0.01");
                            break;
                        case "2":
                            BigDecimal multiply = amt.multiply(couponUser.getCouponTemplateInfo().getCouponAmt()).setScale(2, BigDecimal.ROUND_HALF_UP);
                            newAmt = amt.subtract(multiply);
                            if (newAmt.compareTo(BigDecimal.ZERO) == 0 || newAmt.compareTo(BigDecimal.ZERO) == -1)
                                newAmt = new BigDecimal("0.01");
                            break;
                    }
                    //返回前端优惠券参数
                    resultCouTemList.add(CouponUser.builder()
                            .newAmtByCoupon(newAmt)
                            .couponGetTime(couponUser.getCouponGetTime())
                            .couponEffectiveTime(couponUser.getCouponEffectiveTime())
                            .couponTemplateInfo(couponUser.getCouponTemplateInfo())
                            .build());
                }
            }
        }
        //按照优惠券优惠后金额倒序
        if(null != resultCouTemList && resultCouTemList.size()>1)
            resultCouTemList.stream().sorted(Comparator.comparing(CouponUser::getNewAmtByCoupon).reversed());
        return resultCouTemList;
    }

    /**
     * 用户消费完自动领取
     * @param appUserInfo 用户信息 appUserInfo中stationId 代表油企ID
     * @param stationId 油站ID
     * @param amt       用户加油金额：应收金额；
     */
    @Override
    @Transactional
    synchronized public int initiativeCoupon(AppUserInfo appUserInfo, Integer stationId, BigDecimal amt,String orderNo) {
        int couCount = 0;
        //油站主动发放领取方式
        Map<String, Object> paramCouIs = new HashMap<>();
        paramCouIs.put("issueType", "1");     //领取方式 1，用户消费完系统主动发放；
        paramCouIs.put("curTime", new Date()); //当前时间
        paramCouIs.put("stationId", stationId);

        //查询该couponIssueId是否存在
        CouponIssue ci = couponMapper.selectCouponIssueInfo(CouponIssue.builder().enterpriseId(appUserInfo.getStationId()).issueType("1").build());
        if(ci !=null){
            switch (ci.getThresholdType()){
                case "ladder":
                    paramCouIs.put("thresholdAmt", amt);
                    break;
                case "constant":
                    paramCouIs.put("getThresholdAmt", amt);
                    break;
            }
            List<CouponIssue> couponIssueList = couponMapper.selectCouponListByCouponIssueId(paramCouIs);
            couponIssueList = couponIssueList.stream().sorted(Comparator.comparing(CouponIssue::getThresholdAmt).reversed()).collect(Collectors.toList());
            //查询领取方式
            if(null !=couponIssueList && couponIssueList.size()>0){
                int i1 = couponMapper.selectCouUserSum(CouponUser.builder().mobilePhone(appUserInfo.getMobilePhone()).couponIssueId(couponIssueList.get(0).getCouponIssueId()).build());
                if(i1 <= couponIssueList.get(0).getGiveLimit()){
                    List<CouponUser> saveCouUserList = new ArrayList<>();   //要保存的用户优惠券
                    List<Integer> updateTemIdsMap = new ArrayList<>();      //要更新的优惠券领取数量
                    //用户会员等级
                    List<Grade> gradeList = gradeMapper.selectUserGrade(Grade.builder().enterpriseId(Long.valueOf(appUserInfo.getStationId())).gradeGrowValue(appUserInfo.getGrowUpValue()).deleteFlag("0").build());
                    AppUserSuperDetail appUserSuperDetail = appUserSuperDetailService.selectAppUserSVIPInfoByCurrentTime(AppUserSuperDetail.builder().enterpriseId(Long.valueOf(appUserInfo.getStationId())).userId(Long.valueOf(appUserInfo.getUserId())).build());
                    Map<String, Object> paramOrdCount = new HashMap<>();
                    paramOrdCount.put("stationId", appUserInfo.getStationId());
                    paramOrdCount.put("mobilePhone", appUserInfo.getMobilePhone());
                    int orderCount = payOrderMapper.selectUserOrderCount(paramOrdCount); //当前用户在该油企的订单数
                    log.info("该用户超级会员信息：" + appUserSuperDetail);
                    for (CouponIssue couponIssue : couponIssueList) {
                        if ("ladder".equals(couponIssue.getThresholdType())) {
                            //阶梯使用coupon_issue_relation中字段 threshold_amt；
                            if (amt.compareTo(couponIssue.getThresholdAmt()) >= 0) {
                                if (couponIssue.getEndDate().after(new Date())) {
                                    if (couponIssue.getStartDate().before(new Date())) {
                                        if (null != couponIssue.getCouponTemplateList() && couponIssue.getCouponTemplateList().size() > 0) {
                                            //会员条件是否在等级之内
                                            if ("part".equals(couponIssue.getMemberCondition())) {
                                                if (null != gradeList && gradeList.size() > 0) {
                                                    if (!couponIssue.getMemberLevel().contains(gradeList.get(0).getGradeCode()))
                                                        break;
                                                }
                                                if ("newUser".equals(couponIssue.getMemberTags())) {
                                                    if (orderCount > 0) break;
                                                }
                                                if ("oldUser".equals(couponIssue.getMemberTags())) {
                                                    if (orderCount <= 0) break;
                                                }
                                            }
                                            if ("plus".equals(couponIssue.getMemberCondition())) {
                                                if (null == appUserSuperDetail) break;
                                            }
                                            //客户当天已领取的优惠券模板列
                                            Map<String, Object> param = new HashMap<>();
                                            param.put("couponIssueId", couponIssue.getCouponIssueId());
                                            param.put("mobilePhone", appUserInfo.getMobilePhone());
                                            param.put("startDate", LocalDate.now());
                                            param.put("endDate", LocalDate.now().plusDays(1));
                                            List<CouponUser> couponUserList = couponMapper.selectCouponUserList(param);
                                            if (null != couponUserList && couponUserList.size() > 0) {
                                                //用户已领取的模板id集合
                                                List<Integer> couponTemIds = couponUserList.stream().map(CouponUser::getCouponTemplateId).collect(Collectors.toList());
                                                //开启防作弊
                                                if("0".equals(couponIssue.getAntiCheating()) && couponTemIds.size() >= couponIssue.getCountOfDay()) break;
                                                if("1".equals(couponIssue.getAntiCheating()) && couponTemIds.size() >= 1) break;
                                            }else {
                                                for (CouponTemplate couponTemplate : couponIssue.getCouponTemplateList()){
                                                    if(couponTemplate.getCouponNum() >0){
                                                        Date startTime = new Date();     //开始时间
                                                        Date endTime = new Date();       //结束时间
                                                        //优惠券时间类型
                                                        switch (couponTemplate.getEffectiveTimeType()) {
                                                            case "1":   //固定时间
                                                                //startTime = couponTemplate.getEffectiveTimeStart();
                                                                endTime = couponTemplate.getEffectiveTimeEnd();
                                                                break;
                                                            case "2":   //领取后有效天数
                                                                startTime = new Date();
                                                                Calendar instance = Calendar.getInstance();
                                                                instance.setTime(new Date());
                                                                instance.add(Calendar.DATE, couponTemplate.getEffectiveDayNum());
                                                                endTime = instance.getTime();
                                                                break;
                                                        }
                                                        //要保存的用户优惠券
                                                        saveCouUserList.add(CouponUser.builder()
                                                                .mobilePhone(appUserInfo.getMobilePhone())
                                                                .couponTemplateId(couponTemplate.getCouponTemplateId())
                                                                .couponNo(CryptUtil.useMD5(couponIssue.getEnterpriseId() + Long.toString(System.currentTimeMillis()) + Math.round((Math.random() + 1) * 1000)))
                                                                .couponGetTime(startTime)
                                                                .couponEffectiveTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(endTime))
                                                                .couponIssueId(couponIssue.getCouponIssueId())
                                                                .enterpriseId(couponIssue.getEnterpriseId())
                                                                .couponIssueId(couponIssue.getCouponIssueId())
                                                                .couponIsUsed("0")
                                                                .build());
                                                        //要更新的每个优惠券模板数量
                                                        updateTemIdsMap.add(couponTemplate.getCouponTemplateId());
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        } else {
                            //非阶梯使用coupon_issue中字段 getThresholdAmt；
                            if (amt.compareTo(couponIssue.getGetThresholdAmt()) >= 0) {
                                if (couponIssue.getEndDate().after(new Date())) {
                                    if (couponIssue.getStartDate().before(new Date())) {
                                        if (null != couponIssue.getCouponTemplateList() && couponIssue.getCouponTemplateList().size() > 0) {
                                            //会员条件是否在等级之内
                                            if("part".equals(couponIssue.getMemberCondition())){
                                                if(null !=gradeList && gradeList.size() >0)
                                                    if(!couponIssue.getMemberLevel().contains(gradeList.get(0).getGradeCode())) break;
                                            }
                                            if ("plus".equals(couponIssue.getMemberCondition())) {
                                                if (null == appUserSuperDetail) break;
                                            }
                                            //客户当天已领取的优惠券模板列
                                            Map<String, Object> param = new HashMap<>();
                                            param.put("couponIssueId", couponIssue.getCouponIssueId());
                                            param.put("mobilePhone", appUserInfo.getMobilePhone());
                                            param.put("startDate", LocalDate.now());
                                            param.put("endDate", LocalDate.now().plusDays(1));
                                            List<CouponUser> couponUserList = couponMapper.selectCouponUserList(param);
                                            if (null != couponUserList && couponUserList.size() > 0) {
                                                //用户已领取的模板id集合
                                                List<Integer> couponTemIds = couponUserList.stream().map(CouponUser::getCouponTemplateId).collect(Collectors.toList());
                                                //开启防作弊
                                                if("0".equals(couponIssue.getAntiCheating()) && couponTemIds.size() >= couponIssue.getCountOfDay()) break;
                                                if("1".equals(couponIssue.getAntiCheating()) && couponTemIds.size() >= 1) break;
                                            }else {
                                                for (CouponTemplate couponTemplate : couponIssue.getCouponTemplateList()){
                                                    if(couponTemplate.getCouponNum() >0){
                                                        Date startTime = new Date();     //开始时间
                                                        Date endTime = new Date();       //结束时间
                                                        //优惠券时间类型
                                                        switch (couponTemplate.getEffectiveTimeType()) {
                                                            case "1":   //固定时间
                                                                //startTime = couponTemplate.getEffectiveTimeStart();
                                                                endTime = couponTemplate.getEffectiveTimeEnd();
                                                                break;
                                                            case "2":   //领取后有效天数
                                                                startTime = new Date();
                                                                Calendar instance = Calendar.getInstance();
                                                                instance.setTime(new Date());
                                                                instance.add(Calendar.DATE, couponTemplate.getEffectiveDayNum());
                                                                endTime = instance.getTime();
                                                                break;
                                                        }
                                                        //要保存的用户优惠券
                                                        saveCouUserList.add(CouponUser.builder()
                                                                .mobilePhone(appUserInfo.getMobilePhone())
                                                                .couponTemplateId(couponTemplate.getCouponTemplateId())
                                                                .couponNo(CryptUtil.useMD5(couponIssue.getEnterpriseId() + Long.toString(System.currentTimeMillis()) + Math.round((Math.random() + 1) * 1000)))
                                                                .couponGetTime(startTime)
                                                                .couponEffectiveTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(endTime))
                                                                .couponIssueId(couponIssue.getCouponIssueId())
                                                                .enterpriseId(couponIssue.getEnterpriseId())
                                                                .couponIssueId(couponIssue.getCouponIssueId())
                                                                .couponIsUsed("0")
                                                                .build());
                                                        //要更新的每个优惠券模板数量
                                                        updateTemIdsMap.add(couponTemplate.getCouponTemplateId());
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    //是否有能领取的优惠券
                    System.out.println("用户领取的优惠券：" + saveCouUserList);
                    if (null != saveCouUserList && saveCouUserList.size() > 0) {
                        //批量保存优惠券
                        couCount = couponMapper.saveBatchCouponUser(saveCouUserList);
                        log.info("批量保存的用户优惠券数量：" + couCount);
                        int y = couponMapper.updateBatchCouponTemplate(updateTemIdsMap);
                        log.info("批量更新的优惠券模板减少的模板数量：" + y);
                        if(StringUtils.isNotEmpty(orderNo)){
                            List<PresentCouponUserRecord> savePresentCouponUserRecords = new ArrayList<>();   //要保存的用户优惠券
                            for (CouponUser couponUser : saveCouUserList) {
                                savePresentCouponUserRecords.add(PresentCouponUserRecord.builder()
                                        .couponUserId(couponUser.getCouponUserId().longValue())
                                        .businessName("pay_order")
                                        .orderNo(orderNo)
                                        .build());
                            }
                            presentCouponUserRecordMapper.insertBatch(savePresentCouponUserRecords);
                        }

                    }
                }
            }
        }
        return couCount;
    }

    @Override
    public void pushWxGzhInitiativeCouponInfo(Station station, PayOrder payOrderInfo, int i, AppUserInfo appUserInfo) {
        if (StringUtils.isNotBlank(station.getEnterprise().getTemplateId())) {
            //系统自动发放告诉用户发送优惠券
            if (StringUtils.isNotBlank(appUserInfo.getBlogOpenid())) {
                Enterprise enterprise = enterpriseMapper.selectEnterpriseInfo(station.getEnterpriseId());
                if (enterprise != null && StringUtils.isNotBlank(enterprise.getGzhAppId()) && StringUtils.isNotBlank(enterprise.getGzhAppSecret())) {
                    //新修订
                    WxTemplateMsg wxTemplateMsg = new WxTemplateMsg();
                    wxTemplateMsg.setTemplate_id(station.getEnterprise().getTemplateId());
                    wxTemplateMsg.setTouser(appUserInfo.getBlogOpenid());
                    String url = "https://" + domainName + "/" + enterprise.getEnterpriseId() + "/coupon";
                    wxTemplateMsg.setUrl(url);
                    Map<String, WxTemplateData> templateDataMap = new HashMap<>();
                    templateDataMap.put("first", WxTemplateData.builder().value("恭喜您获得 " + i + " 优惠券，请点击查看").color("#0080FF").build());
                    templateDataMap.put("keyword1", WxTemplateData.builder().value("点击查看").color("#0080FF").build());
                    templateDataMap.put("keyword2", WxTemplateData.builder().value(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())).color("#0080FF").build());
                    wxTemplateMsg.setData(templateDataMap);
                    wxPushUtil.sendTemplateMsg(enterprise.getGzhAppId(), enterprise.getGzhAppSecret(), wxTemplateMsg);
                }
            }
        }
    }

    @Override
    public void pushWxGzhInitiativeCouponInfo(Enterprise enterprise, int i, AppUserInfo appUserInfo) {
        if (StringUtils.isNotBlank(enterprise.getTemplateId())) {
            //系统自动发放告诉用户发送优惠券
            if (StringUtils.isNotBlank(appUserInfo.getBlogOpenid())) {
                if (enterprise != null && StringUtils.isNotBlank(enterprise.getGzhAppId()) && StringUtils.isNotBlank(enterprise.getGzhAppSecret())) {
                    //新修订
                    WxTemplateMsg wxTemplateMsg = new WxTemplateMsg();
                    wxTemplateMsg.setTemplate_id(enterprise.getTemplateId());
                    wxTemplateMsg.setTouser(appUserInfo.getBlogOpenid());
                    String url = "https://" + domainName + "/" + enterprise.getEnterpriseId() + "/coupon";
                    wxTemplateMsg.setUrl(url);
                    Map<String, WxTemplateData> templateDataMap = new HashMap<>();
                    templateDataMap.put("first", WxTemplateData.builder().value("恭喜您获得 " + i + " 优惠券，请点击查看").color("#0080FF").build());
                    templateDataMap.put("keyword1", WxTemplateData.builder().value("点击查看").color("#0080FF").build());
                    templateDataMap.put("keyword2", WxTemplateData.builder().value(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())).color("#0080FF").build());
                    wxTemplateMsg.setData(templateDataMap);
                    wxPushUtil.sendTemplateMsg(enterprise.getGzhAppId(), enterprise.getGzhAppSecret(), wxTemplateMsg);
                }
            }
        }
    }

    /**
     * 用户开通超级会员后自动发放优惠券
     * @param appUserInfo
     * @param appUserInfo
     * @param appUserSuper
     */
    @Override
    @Transactional
    synchronized public void userSuperCoupon(AppUserInfo appUserInfo, AppUserSuper appUserSuper) {
        //油站主动发放领取方式
        Map<String, Object> paramCouIs = new HashMap<>();
        paramCouIs.put("issueType", "1");     //领取方式 1，主动发放；
        paramCouIs.put("curTime", new Date()); //当前时间
        paramCouIs.put("couponIssueId", appUserSuper.getCouponIssueId());
        List<CouponIssue> couponIssueList = couponMapper.selectCouponListByCouponIssueId(paramCouIs);
        //查询领取方式
        if (null != couponIssueList && couponIssueList.size() > 0) {
            //int userIssueGiveCount = couponMapper.selectUserIssueGiveCount(CouponUserGiveCount.builder().mobilePhone(appUserInfo.getMobilePhone()).couponIssueId(couponIssueList.get(0).getCouponIssueId()).build());
            int i1 = couponMapper.selectCouUserSum(CouponUser.builder().mobilePhone(appUserInfo.getMobilePhone()).couponIssueId(couponIssueList.get(0).getCouponIssueId()).build());
            if (i1 <= couponIssueList.get(0).getGiveLimit()) {
                List<CouponUser> saveCouUserList = new ArrayList<>();   //要保存的用户优惠券
                List<Integer> updateTemIdsMap = new ArrayList<>();      //要更新的优惠券领取数量
                for (CouponIssue couponIssue : couponIssueList) {
                    if (couponIssue.getEndDate().after(new Date())) {
                        if (couponIssue.getStartDate().before(new Date())) {
                            if (null != couponIssue.getCouponTemplateList() && couponIssue.getCouponTemplateList().size() > 0) {

                                //客户当天已领取的优惠券模板列
                                Map<String, Object> param = new HashMap<>();
                                param.put("couponIssueId", couponIssue.getCouponIssueId());
                                param.put("mobilePhone", appUserInfo.getMobilePhone());
                                param.put("startDate", LocalDate.now());
                                param.put("endDate", LocalDate.now().plusDays(1));
                                List<CouponUser> couponUserList = couponMapper.selectCouponUserList(param);
                                if (null != couponUserList && couponUserList.size() > 0) {
                                    //用户已领取的模板id集合
                                    List<Integer> couponTemIds = couponUserList.stream().map(CouponUser::getCouponTemplateId).collect(Collectors.toList());
                                    //开启防作弊
                                    if("0".equals(couponIssue.getAntiCheating()) && couponTemIds.size() >= couponIssue.getCountOfDay()) break;
                                    if("1".equals(couponIssue.getAntiCheating()) && couponTemIds.size() >= 1) break;
                                }else {
                                    for (CouponTemplate couponTemplate : couponIssue.getCouponTemplateList()){
                                        if(couponTemplate.getCouponNum() >0){
                                            Date startTime = new Date();     //开始时间
                                            Date endTime = new Date();       //结束时间
                                            //优惠券时间类型
                                            switch (couponTemplate.getEffectiveTimeType()) {
                                                case "1":   //固定时间
                                                    //startTime = couponTemplate.getEffectiveTimeStart();
                                                    endTime = couponTemplate.getEffectiveTimeEnd();
                                                    break;
                                                case "2":   //领取后有效天数
                                                    startTime = new Date();
                                                    Calendar instance = Calendar.getInstance();
                                                    instance.setTime(new Date());
                                                    instance.add(Calendar.DATE, couponTemplate.getEffectiveDayNum());
                                                    endTime = instance.getTime();
                                                    break;
                                            }
                                            //要保存的用户优惠券
                                            saveCouUserList.add(CouponUser.builder()
                                                    .mobilePhone(appUserInfo.getMobilePhone())
                                                    .couponTemplateId(couponTemplate.getCouponTemplateId())
                                                    .couponNo(CryptUtil.useMD5(couponIssue.getEnterpriseId() + Long.toString(System.currentTimeMillis()) + Math.round((Math.random() + 1) * 1000)))
                                                    .couponGetTime(startTime)
                                                    .couponEffectiveTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(endTime))
                                                    .couponIssueId(couponIssue.getCouponIssueId())
                                                    .enterpriseId(couponIssue.getEnterpriseId())
                                                    .couponIssueId(couponIssue.getCouponIssueId())
                                                    .couponIsUsed("0")
                                                    .build());
                                            //要更新的每个优惠券模板数量
                                            updateTemIdsMap.add(couponTemplate.getCouponTemplateId());
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                //是否有能领取的优惠券
                System.out.println("用户领取的优惠券：" + saveCouUserList);
                if (null != saveCouUserList && saveCouUserList.size() > 0) {
                    //批量保存优惠券
                    int i = couponMapper.saveBatchCouponUser(saveCouUserList);
                    log.info("批量保存的用户优惠券数量：" + i);
                    int y = couponMapper.updateBatchCouponTemplate(updateTemIdsMap);
                    log.info("批量更新的优惠券模板减少的模板数量：" + y);
                }
            }
        }
    }

    @Override
    public List<CouponUser> selectCouponUserList(Map<String, Object> param) {
        return couponMapper.selectCouponUserList(param);
    }



    /**
     * 用户消费完自动领取
     * @param appUserInfo 用户信息 appUserInfo中stationId 代表油企ID
     * @param stationId   油站ID
     * @param amt         用户加油金额：应收金额；
     */
    // 未启用该接口
    @Override
    @Transactional
    synchronized public int initiativeCouponV2(AppUserInfo appUserInfo, Integer stationId, BigDecimal amt) {
        int couCount = 0;
        //油站主动发放领取方式
        Map<String, Object> paramCouIs = new HashMap<>();
        paramCouIs.put("issueType", "1");     //领取方式 1，用户消费完系统主动发放；
        paramCouIs.put("curTime", new Date()); //当前时间
        paramCouIs.put("stationId", stationId);

        //查询该couponIssueId是否存在
        CouponIssue ci = couponMapper.selectCouponIssueInfo(CouponIssue
                .builder()
                .enterpriseId(appUserInfo.getStationId())
                .issueType("1")
                .build()
        );

        if (ci == null) {
            return 0;
        }

        switch (ci.getThresholdType()) {
            case "ladder":
                paramCouIs.put("thresholdAmt", amt);
                break;
            case "constant":
                paramCouIs.put("getThresholdAmt", amt);
                break;
        }

        List<CouponIssue> couponIssueList = couponMapper.selectCouponListByCouponIssueId(paramCouIs);
        couponIssueList = couponIssueList
                .stream()
                .sorted(Comparator
                        .comparing(CouponIssue::getThresholdAmt).reversed())
                .collect(Collectors.toList()
                );

        if (null == couponIssueList || couponIssueList.size() <= 0) {
            return 0;
        }

        // 用户领取过的总优惠劵
        int i1 = couponMapper.selectCouUserSum(CouponUser
                .builder()
                .mobilePhone(appUserInfo.getMobilePhone())
                .couponIssueId(couponIssueList.get(0).getCouponIssueId())
                .build()
        );


        if (i1 > couponIssueList.get(0).getGiveLimit()) {
            return 0;
        }


        List<CouponUser> saveCouUserList = new ArrayList<>();   // 要保存的用户优惠券
        List<Integer> updateTemIdsMap = new ArrayList<>();      // 要更新的优惠券领取数量

        //用户会员等级
        List<Grade> gradeList = gradeMapper.selectUserGrade(Grade
                .builder()
                .enterpriseId(Long.valueOf(appUserInfo.getStationId()))
                .gradeGrowValue(appUserInfo.getGrowUpValue())
                .deleteFlag("0")
                .build()
        );

        AppUserSuperDetail appUserSuperDetail = appUserSuperDetailService.selectAppUserSVIPInfoByCurrentTime(AppUserSuperDetail
                .builder()
                .enterpriseId(Long.valueOf(appUserInfo.getStationId()))
                .userId(Long.valueOf(appUserInfo.getUserId()))
                .build()
        );

        Map<String, Object> paramOrdCount = new HashMap<>();
        paramOrdCount.put("stationId", appUserInfo.getStationId());
        paramOrdCount.put("mobilePhone", appUserInfo.getMobilePhone());

        int orderCount = payOrderMapper.selectUserOrderCount(paramOrdCount); //当前用户在该油企的订单数
        log.info("该用户超级会员信息：" + appUserSuperDetail);

        for (CouponIssue couponIssue : couponIssueList) {
            if ("ladder".equals(couponIssue.getThresholdType())) {
                //阶梯使用coupon_issue_relation中字段 threshold_amt；
                if (amt.compareTo(couponIssue.getThresholdAmt()) >= 0) {
                    if (couponIssue.getEndDate().after(new Date())) {
                        if (couponIssue.getStartDate().before(new Date())) {
                            if (null != couponIssue.getCouponTemplateList() && couponIssue.getCouponTemplateList().size() > 0) {
                                //会员条件是否在等级之内
                                if ("part".equals(couponIssue.getMemberCondition())) {
                                    if (null != gradeList && gradeList.size() > 0) {
                                        if (!couponIssue.getMemberLevel().contains(gradeList.get(0).getGradeCode()))
                                            break;
                                    }
                                    if ("newUser".equals(couponIssue.getMemberTags())) {
                                        if (orderCount > 0) break;
                                    }
                                    if ("oldUser".equals(couponIssue.getMemberTags())) {
                                        if (orderCount <= 0) break;
                                    }
                                }
                                if ("plus".equals(couponIssue.getMemberCondition())) {
                                    if (null == appUserSuperDetail) break;
                                }
                                //客户当天已领取的优惠券模板列
                                Map<String, Object> param = new HashMap<>();
                                param.put("couponIssueId", couponIssue.getCouponIssueId());
                                param.put("mobilePhone", appUserInfo.getMobilePhone());
                                param.put("startDate", LocalDate.now());
                                param.put("endDate", LocalDate.now().plusDays(1));
                                List<CouponUser> couponUserList = couponMapper.selectCouponUserList(param);
                                if (null != couponUserList && couponUserList.size() > 0) {
                                    //用户已领取的模板id集合
                                    List<Integer> couponTemIds = couponUserList.stream().map(CouponUser::getCouponTemplateId).collect(Collectors.toList());
                                    //开启防作弊
                                    if ("0".equals(couponIssue.getAntiCheating()) && couponTemIds.size() >= couponIssue.getCountOfDay())
                                        break;
                                    if ("1".equals(couponIssue.getAntiCheating()) && couponTemIds.size() >= 1) break;
                                } else {
                                    for (CouponTemplate couponTemplate : couponIssue.getCouponTemplateList()) {
                                        if (couponTemplate.getCouponNum() > 0) {
                                            Date startTime = new Date();     //开始时间
                                            Date endTime = new Date();       //结束时间
                                            //优惠券时间类型
                                            switch (couponTemplate.getEffectiveTimeType()) {
                                                case "1":   //固定时间
                                                    //startTime = couponTemplate.getEffectiveTimeStart();
                                                    endTime = couponTemplate.getEffectiveTimeEnd();
                                                    break;
                                                case "2":   //领取后有效天数
                                                    startTime = new Date();
                                                    Calendar instance = Calendar.getInstance();
                                                    instance.setTime(new Date());
                                                    instance.add(Calendar.DATE, couponTemplate.getEffectiveDayNum());
                                                    endTime = instance.getTime();
                                                    break;
                                            }
                                            //要保存的用户优惠券
                                            saveCouUserList.add(CouponUser.builder()
                                                    .mobilePhone(appUserInfo.getMobilePhone())
                                                    .couponTemplateId(couponTemplate.getCouponTemplateId())
                                                    .couponNo(CryptUtil.useMD5(couponIssue.getEnterpriseId() + Long.toString(System.currentTimeMillis()) + Math.round((Math.random() + 1) * 1000)))
                                                    .couponGetTime(startTime)
                                                    .couponEffectiveTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(endTime))
                                                    .couponIssueId(couponIssue.getCouponIssueId())
                                                    .enterpriseId(couponIssue.getEnterpriseId())
                                                    .couponIssueId(couponIssue.getCouponIssueId())
                                                    .couponIsUsed("0")
                                                    .build());
                                            //要更新的每个优惠券模板数量
                                            updateTemIdsMap.add(couponTemplate.getCouponTemplateId());
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            } else {
                //非阶梯使用coupon_issue中字段 getThresholdAmt；
                if (amt.compareTo(couponIssue.getGetThresholdAmt()) >= 0) {
                    if (couponIssue.getEndDate().after(new Date())) {
                        if (couponIssue.getStartDate().before(new Date())) {
                            if (null != couponIssue.getCouponTemplateList() && couponIssue.getCouponTemplateList().size() > 0) {
                                //会员条件是否在等级之内
                                if ("part".equals(couponIssue.getMemberCondition())) {
                                    if (null != gradeList && gradeList.size() > 0)
                                        if (!couponIssue.getMemberLevel().contains(gradeList.get(0).getGradeCode()))
                                            break;
                                }
                                if ("plus".equals(couponIssue.getMemberCondition())) {
                                    if (null == appUserSuperDetail) break;
                                }
                                //客户当天已领取的优惠券模板列
                                Map<String, Object> param = new HashMap<>();
                                param.put("couponIssueId", couponIssue.getCouponIssueId());
                                param.put("mobilePhone", appUserInfo.getMobilePhone());
                                param.put("startDate", LocalDate.now());
                                param.put("endDate", LocalDate.now().plusDays(1));
                                List<CouponUser> couponUserList = couponMapper.selectCouponUserList(param);
                                if (null != couponUserList && couponUserList.size() > 0) {
                                    //用户已领取的模板id集合
                                    List<Integer> couponTemIds = couponUserList.stream().map(CouponUser::getCouponTemplateId).collect(Collectors.toList());
                                    //开启防作弊
                                    if ("0".equals(couponIssue.getAntiCheating()) && couponTemIds.size() >= couponIssue.getCountOfDay())
                                        break;
                                    if ("1".equals(couponIssue.getAntiCheating()) && couponTemIds.size() >= 1) break;
                                } else {
                                    for (CouponTemplate couponTemplate : couponIssue.getCouponTemplateList()) {
                                        if (couponTemplate.getCouponNum() > 0) {
                                            Date startTime = new Date();     //开始时间
                                            Date endTime = new Date();       //结束时间
                                            //优惠券时间类型
                                            switch (couponTemplate.getEffectiveTimeType()) {
                                                case "1":   //固定时间
                                                    //startTime = couponTemplate.getEffectiveTimeStart();
                                                    endTime = couponTemplate.getEffectiveTimeEnd();
                                                    break;
                                                case "2":   //领取后有效天数
                                                    startTime = new Date();
                                                    Calendar instance = Calendar.getInstance();
                                                    instance.setTime(new Date());
                                                    instance.add(Calendar.DATE, couponTemplate.getEffectiveDayNum());
                                                    endTime = instance.getTime();
                                                    break;
                                            }
                                            //要保存的用户优惠券
                                            saveCouUserList.add(CouponUser.builder()
                                                    .mobilePhone(appUserInfo.getMobilePhone())
                                                    .couponTemplateId(couponTemplate.getCouponTemplateId())
                                                    .couponNo(CryptUtil.useMD5(couponIssue.getEnterpriseId() + Long.toString(System.currentTimeMillis()) + Math.round((Math.random() + 1) * 1000)))
                                                    .couponGetTime(startTime)
                                                    .couponEffectiveTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(endTime))
                                                    .couponIssueId(couponIssue.getCouponIssueId())
                                                    .enterpriseId(couponIssue.getEnterpriseId())
                                                    .couponIssueId(couponIssue.getCouponIssueId())
                                                    .couponIsUsed("0")
                                                    .build());
                                            //要更新的每个优惠券模板数量
                                            updateTemIdsMap.add(couponTemplate.getCouponTemplateId());
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        //是否有能领取的优惠券
        System.out.println("用户领取的优惠券：" + saveCouUserList);
        if (null != saveCouUserList && saveCouUserList.size() > 0) {
            //批量保存优惠券
            couCount = couponMapper.saveBatchCouponUser(saveCouUserList);
            log.info("批量保存的用户优惠券数量：" + couCount);
            int y = couponMapper.updateBatchCouponTemplate(updateTemIdsMap);
            log.info("批量更新的优惠券模板减少的模板数量：" + y);

        }


        return couCount;
    }

    @Override
    public BigDecimal queryMinUseCouponAtmByCouponTemlete(Integer id) {
        return couponMapper.queryMinUseCouponAtmByCouponTemlete(id);
    }

    @SneakyThrows
    @Override
    @Transactional
    public ResultData<?> carWashCouponDestroy(carWashPaymentDto cw) {
        //获取洗车券信息
        List<CouponUser> couponUsersInfo = couponService.selectUserAllCoupons(CouponUser.builder().couponNo(cw.getCouponNo()).build());
        log.info("无此优惠券：{}", couponUsersInfo);
        if (couponUsersInfo.isEmpty()) {
            return ResultData.error("无此优惠券");
        }
        //获取核销人员信息
        SysUser sysUser = posMachineService.selectUserByUserName(cw.getUserName());
        log.info("获取核销人员信息：{}", sysUser);
        //核销洗车券
        CouponUser couponUser = couponUsersInfo.get(0);
        log.info("查询油品信息入参：{}", cw.getOilName());
        Oil oil = enterpriseService.selectOilByOilId(Integer.valueOf(cw.getOilName()));
        log.info("查询油品信息出参：{}", oil);
        String enterpriseId = sysUser.getEnterpriseId();
        String couponUserEnterpriseId = couponUser.getEnterpriseId().toString();
        if (!enterpriseId.equals(couponUserEnterpriseId)) {
            return ResultData.error(CodeMsg.CAN_BE_HERE);
        }
        String couponStaNames = couponUser.getCouponStaNames();
        Station station = enterpriseService.selectStationById(Integer.valueOf(sysUser.getStationId()));
        String stationName = station.getStationName();
        List<String> nameList = Arrays.asList(couponStaNames.split(","));

        if (!nameList.contains(stationName)) {
            return ResultData.error(CodeMsg.CAN_BE_HERE);
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (simpleDateFormat.parse(couponUsersInfo.get(0).getCouponEffectiveTime()).after(new Date())) {

            //状态
            if ("0".equals(couponUser.getCouponIsUsed())) {


                CouponTemplate couponTemplateInfo = couponUser.getCouponTemplateInfo();

                String effectiveTimeType = couponTemplateInfo.getEffectiveTimeType();
                if (null != effectiveTimeType && effectiveTimeType.equals("1")){
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String effectiveTimeEnd = sdf.format(couponTemplateInfo.getEffectiveTimeEnd());
                    String effectiveTimeStart = sdf.format(couponTemplateInfo.getEffectiveTimeStart());
                    if (simpleDateFormat.parse(effectiveTimeStart).after(new Date())){
                        return ResultData.error(CodeMsg.TIME_IS_NOT_UP);
                    }

                }

                //判断是否洗车券及状态
                if (ObjectUtils.isNotEmpty(couponTemplateInfo) && "4".equals(couponTemplateInfo.getCouponType()) && "1".equals(couponTemplateInfo.getCouponTemplateStatus())) {
                    if (null == couponTemplateInfo.getVerification() || Arrays.asList(couponTemplateInfo.getVerification().split(",")).contains(sysUser.getStationId())) {
                        //更新用户优惠券信息
                        this.updateCouponUser(CouponUser.builder().couponNo(cw.getCouponNo()).verificationTime(new Date()).couponIsUsed("1").verificationUserAccount(cw.getUserName()).verificationUserPhone(sysUser.getPhonenumber()).build());
                        //更新优惠券使用模板数量
                        this.updateCouponTemplate(CouponTemplate.builder().couponTemplateId(couponTemplateInfo.getCouponTemplateId()).useCouponNum(couponTemplateInfo.getUseCouponNum() + 1).build());
                        //生成洗车订单
                        PayOrder payOrderParam = setAddPayOrderParam(sysUser, couponUser, cw);
                        log.info("添加优惠券订单入参：{}", payOrderParam);
                        PayOrder payOrder = payOrderService.posAddCarWashOrder(payOrderParam);
                        log.info("添加优惠券订单出参：{}", payOrder);
                        if (ObjectUtils.isNotEmpty(payOrder)) {
                            return ResultData.success(payOrder);
                        }
                    }
                }
            }
            return ResultData.error(CodeMsg.CAR_WASH_TICKET_EXPIRED);
        }
        return ResultData.error(CodeMsg.TIME_IS_NOT_UP);
    }




    @Override
    public CouponInfo selectCouponTemInfoById(Long couponInfoId) {
        return couponInfoMapper.selectCouponInfoById(couponInfoId.intValue());
    }


    @Override
    public CouponInfoSettingDetail getCouponInfoIdByCustomerCardUseRecord(CustomerCardUseRecord cardRecordByOrderNo, String payType) {
        CustomerCardSettingDetail form = new CustomerCardSettingDetail();
        //Integer stationId = cardRecordByOrderNo.getStationId();
        //Station station = stationMapper.selectStationById(stationId);
        form.setActivityType(CustomerCardSettingDetail.ACTIVITYTYPE_COUPON);//只查询优惠劵的，增额活动不处理
        form.setDelFlag("0");
        form.setCardType(cardRecordByOrderNo.getCardOilsType());
        form.setEnterpriseId(Long.valueOf(cardRecordByOrderNo.getEnterpriseId()));
        form.setStationId(Long.valueOf(cardRecordByOrderNo.getStationId()));
        form.setStatus("NORMAL");
        form.setPayType(payType);
        form.setActivityMode(CustomerCardSettingDetail.ACTIVITY_MODE_RECHARGE);
//        if(cardRecordByOrderNo.getCcsdId()!=null){
//            form.setCardSettingDetailId(cardRecordByOrderNo.getCcsdId().intValue());
//        }


        BigDecimal amt = cardRecordByOrderNo.getAmt();
        form.setNowDate(new Date());
        form.setWeeklySelection(CustomerCardSettingDetail.dateToWeek(new Date()));
        form.setMonthlySelection(CustomerCardSettingDetail.dateToMonth(new Date()));

        List<CustomerCardSettingDetail> customerCardSettingDetails = electronicMembershipCardService.selectCardSettingDetail(form);

        if (!customerCardSettingDetails.isEmpty()) {
            CouponInfoSettingDetail couponInfoSettingDetail = new CouponInfoSettingDetail();
            couponInfoSettingDetail.setEnterpriseId(Long.valueOf(cardRecordByOrderNo.getEnterpriseId()));
            List<Integer> ccsdIds = customerCardSettingDetails.stream().filter(d->customerCardSettingDetailService.checkEffectiveTime(d)).map(CustomerCardSettingDetail::getCardSettingDetailId).collect(Collectors.toList());
            if(ccsdIds.size()>0){
                List<CustomerCardSettingDetailContent> contentList = electronicMembershipCardService.queryCardSettingDetailContentsByCcsdIdsBetweenAmt(ccsdIds, amt);
                for (CustomerCardSettingDetailContent content : contentList) {
                    if (amt.compareTo(content.getRechargeAmtLowerLimit()) >= 0 && amt.compareTo(content.getRechargeAmtUpperLimit()) < 0) {
                        couponInfoSettingDetail.setCcsdId(content.getCcsdId());
                        String couponIssueIds = content.getCouponIssueIds();
                        List<String> couponIds;
                        if (StringUtils.isNotEmpty(couponIssueIds)) {
                            String[] split = couponIssueIds.split(",");
                            couponIds = new ArrayList<>(Arrays.asList(split));
                        }else{
                            couponIds = Collections.emptyList();
                        }
                        couponInfoSettingDetail.setCouponIds(couponIds);
                        return couponInfoSettingDetail;
                    }
                }
            }

        }

//        for (CustomerCardSettingDetail cardDetail : customerCardSettingDetails) {
//            CustomerCardSettingDetailContent contentQuery=new CustomerCardSettingDetailContent();
//            contentQuery.setCcsdId(cardDetail.getCardSettingDetailId().longValue());
//            List<CustomerCardSettingDetailContent> contentList=electronicMembershipCardService.getCardSettingDetailContents(contentQuery);
//            for (CustomerCardSettingDetailContent content : contentList) {
//                if (amt.compareTo(content.getRechargeAmtLowerLimit()) >=0 && amt.compareTo(content.getRechargeAmtUpperLimit())<0) {
//                    couponInfoSettingDetail.setCcsdId(cardDetail.getCardSettingDetailId().longValue());
//                    String couponIssueIds = content.getCouponIssueIds();
//                    List<String> couponIds=new ArrayList<>();
//                    if(StringUtils.isNotEmpty(couponIssueIds)){
//                        String[] split = couponIssueIds.split(",");
//                        couponIds=new ArrayList<>(Arrays.asList(split));
//                    }
//                        couponInfoSettingDetail.setCouponIds(couponIds);
//
//
//                    return couponInfoSettingDetail;
//
//                }
//            }
//        }
        return null;
    }


    @Override
    public List<String> getCouponActivity(Integer enterpriseId) {

        return couponMapper.getCouponActivity(enterpriseId);
    }

    @SneakyThrows
    @Override
    public String getRegisterCoupon(Integer enterpriseId, String mobilePhone) {
        //睡眠一秒 等发券
        TimeUnit.SECONDS.sleep(1);
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        ResultData resultData = null;

        List<CouponUser> couponUsers = couponService.selectUsedCoupons(CouponUser.builder()
                .mobilePhone(mobilePhone)
                .enterpriseId(enterpriseId)
                .couponIsUsed("0").build());

        if (CollectionUtil.isNotEmpty(couponUsers)) {
            resultData = ResultData.success(couponUsers);
        } else {
            resultData = ResultData.success(null);
        }
        return gson.toJson(resultData);
    }

    @Override
    public List<CouponInfo> getCouponInfoByCouponIssue(List<String> couponIssues) {
        return couponMapper.getCouponInfoByCouponIssue(couponIssues);
    }

    @Override
    @Transactional
    @SneakyThrows
    public ResultData<?> newCarWashCouponDestroy(newCarWashPaymetDto cw) {
        log.info("核销码：{}", cw.getCouponNo());
        String couponNo = cw.getCouponNo();
        String[] prefix = couponNo.split("_");
        String prefix1 = prefix[0];
        if (prefix1.equals("xcq")) {
            //去到核销码前缀
            cw.setCouponNo(prefix[1]);
            //获取洗车券信息
            List<CouponUser> couponUsersInfo = couponService.selectUserAllCoupons(CouponUser.builder().couponNo(cw.getCouponNo()).build());
            log.info("获取洗车优惠券信息：{}", couponUsersInfo);
            if (couponUsersInfo.isEmpty()) {
                return ResultData.error(CodeMsg.NO_CAR_WASH_TICKET);
            }
            //获取核销人员信息
            SysUser sysUser = posMachineService.selectUserByUserId(cw.getOilPersonnelId());
            log.info("获取核销人员信息：{}", sysUser);
            //核销洗车券
            CouponUser couponUser = couponUsersInfo.get(0);
            //根据油站id获取油品信息
            List<Oil> listByStationId = staOilGunMapper.getListByStationId(Long.valueOf(cw.getStationId()));
            String oilType = null;
            if (CollectionUtil.isNotEmpty(listByStationId)) {
                for (Oil oil : listByStationId) {
                    //后台也要改 cancelCouponService.cancelCoupon
                    if (oil.getOilClass().equals("服务")){
                        oilType = "洗车";
                        break;
                    }
                }
            }
            String enterpriseId = sysUser.getEnterpriseId();
            String couponUserEnterpriseId = couponUser.getEnterpriseId().toString();
            if (!enterpriseId.equals(couponUserEnterpriseId)) {
                return ResultData.error(CodeMsg.CAN_BE_HERE);
            }
            String couponStaNames = couponUser.getCouponStaNames();
            Station station = enterpriseService.selectStationById(Integer.valueOf(sysUser.getStationId()));
            String stationName = station.getStationName();
            List<String> nameList = Arrays.asList(couponStaNames.split(","));

            if (!nameList.contains(stationName)) {
                return ResultData.error(CodeMsg.CAN_BE_HERE);
            }
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (simpleDateFormat.parse(couponUsersInfo.get(0).getCouponEffectiveTime()).after(new Date())) {

                //状态
                if ("0".equals(couponUser.getCouponIsUsed())) {

                    if (null == oilType) {
                        return ResultData.error(CodeMsg.NOT_A_CAR_WASH);
                    }
                    CouponTemplate couponTemplateInfo = couponUser.getCouponTemplateInfo();

                    String effectiveTimeType = couponTemplateInfo.getEffectiveTimeType();
                    if (null != effectiveTimeType && effectiveTimeType.equals("1")) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String effectiveTimeEnd = sdf.format(couponTemplateInfo.getEffectiveTimeEnd());
                        String effectiveTimeStart = sdf.format(couponTemplateInfo.getEffectiveTimeStart());
                        if (simpleDateFormat.parse(effectiveTimeStart).after(new Date())) {
                            return ResultData.error(CodeMsg.TIME_IS_NOT_UP);
                        }

                    }

                    //判断是否洗车券及状态
                    if (ObjectUtils.isNotEmpty(couponTemplateInfo) && "4".equals(couponTemplateInfo.getCouponType()) && "1".equals(couponTemplateInfo.getCouponTemplateStatus())) {
                        if (null == couponTemplateInfo.getVerification() || Arrays.asList(couponTemplateInfo.getVerification().split(",")).contains(sysUser.getStationId())) {
                            //更新用户优惠券信息
                            int i1 = this.updateCouponUser(CouponUser.builder().couponNo(cw.getCouponNo()).verificationTime(new Date()).couponIsUsed("1").verificationUserAccount(sysUser.getUserName()).verificationUserPhone(sysUser.getPhonenumber()).build());
                            //更新优惠券使用模板数量
                            int i = this.updateCouponTemplate(CouponTemplate.builder().couponTemplateId(couponTemplateInfo.getCouponTemplateId()).useCouponNum(couponTemplateInfo.getUseCouponNum() + 1).build());
                            //记录在优惠券核销表
                            Integer i2 = addCancelCouponRecord(couponUser, cw);
                            if (i != 1 || i1 != 1 || i2 != 1) {
                                log.error("更新用户优惠券信息:{},更新优惠券使用模板数量:{},记录优惠券核销表:{}", i, i1, i2);
                                throw new CustomException("核销失败");
                            }
                            return ResultData.success("核销成功");
                        }
                    }
                }
                return ResultData.error(CodeMsg.CAR_WASH_TICKET_EXPIRED);
            }
            return ResultData.error(CodeMsg.TIME_IS_NOT_UP);
        }
        return ResultData.error(CodeMsg.THERE_IS_NO_SUCH_WRITE_OFF);
    }

    @Override
    @Transactional
    @SneakyThrows
    public ResultData<?> couponDestroyList(CouponPaymetDto cw) {
        log.info("核销码：{}", cw.getCouponNo());
        String couponNo = cw.getCouponNo();
       int verificationType = cw.getVerificationType();
        Date  couponVTime = cw.getCouponVtime();
        //String[] prefix = couponNo.split("_");
        //String prefix1 = prefix[0];
        cw.setCouponNo(couponNo);
        //获取券信息
        List<CouponUser> couponUsersInfo = couponService.selectUserAllCoupons(CouponUser.builder().couponNo(cw.getCouponNo()).build());
        log.info("获取优惠券信息：{}", couponUsersInfo);
        if (couponUsersInfo.isEmpty()) {
            return ResultData.error("没找到优惠券", couponNo);
        }

        //核销洗车券
        CouponUser couponUser = couponUsersInfo.get(0);
       String issueName  = couponUser.getCouponTemplateInfo().getCouponRemark();
        String mobilePhone = couponUser.getMobilePhone();
        AppUserInfo appUserInfo = new AppUserInfo();
        appUserInfo.setMobilePhone(mobilePhone);
        appUserInfo.setStationId(couponUser.getEnterpriseId());
        AppUserInfo appUserInfoDetail = appUserInfoService.getAppUserInfo(appUserInfo);
        String blogNickName =  appUserInfoDetail.getBlogNickName()!=null ?appUserInfoDetail.getBlogNickName():"未知用户";


        //根据油站id获取油品信息
        List<Oil> listByStationId = staOilGunMapper.getListByStationId(Long.valueOf(cw.getStationId()));
        String couponStaNames = couponUser.getCouponStaNames();
        Station station = enterpriseService.selectStationById(cw.getStationId());
        String stationName = station.getStationName();
        List<String> nameList = Arrays.asList(couponStaNames.split(","));

        if (!nameList.contains(stationName)) {
            return ResultData.error(CodeMsg.CAN_BE_HERE);
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (simpleDateFormat.parse(couponUsersInfo.get(0).getCouponEffectiveTime()).after(new Date())) {

            //状态
            if ("0".equals(couponUser.getCouponIsUsed())) {

                CouponTemplate couponTemplateInfo = couponUser.getCouponTemplateInfo();

                String effectiveTimeType = couponTemplateInfo.getEffectiveTimeType();
                if (null != effectiveTimeType && effectiveTimeType.equals("1")) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String effectiveTimeEnd = sdf.format(couponTemplateInfo.getEffectiveTimeEnd());
                    String effectiveTimeStart = sdf.format(couponTemplateInfo.getEffectiveTimeStart());
                    if (simpleDateFormat.parse(effectiveTimeStart).after(new Date())) {
                        return ResultData.error(CodeMsg.TIME_IS_NOT_UP);
                    }

                }

                //判断是否洗车券及状态
                if (ObjectUtils.isNotEmpty(couponTemplateInfo)  && "1".equals(couponTemplateInfo.getCouponTemplateStatus())) {
                    if (null == couponTemplateInfo.getVerification() || Arrays.asList(couponTemplateInfo.getVerification().split(",")).contains(cw.getStationId())) {
                        //更新用户优惠券信息
                        CouponUser couponUUss = CouponUser.builder().couponNo(cw.getCouponNo()).verificationTime(couponVTime).couponIsUsed("1").verificationUserAccount(blogNickName).verificationUserPhone(mobilePhone).build();
                        if(verificationType == 1){
                            couponUUss.setVerificationType(1);
                        }else{
                            couponUUss.setVerificationType(2);
                        }
                        int i1 = this.updateCouponUser(couponUUss);
                        //更新优惠券使用模板数量
                        int i = this.updateCouponTemplate(CouponTemplate.builder().couponTemplateId(couponTemplateInfo.getCouponTemplateId()).useCouponNum(couponTemplateInfo.getUseCouponNum() + 1).build());
                        //记录在优惠券核销表
                        Integer i2 = addCancelCouponRecord(couponUser, cw);
                        if (i != 1 || i1 != 1 || i2 != 1) {
                            log.error("更新用户优惠券信息:{},更新优惠券使用模板数量:{},记录优惠券核销表:{}", i, i1, i2);
                            throw new CustomException("核销失败");
                        }
                        return ResultData.success(couponUser.getCouponType());
                    }
                }
            }
            return ResultData.error(CodeMsg.CAR_WASH_TICKET_EXPIRED);
        }
        return ResultData.error(CodeMsg.TIME_IS_NOT_UP);

    }

    @Override
    @Transactional
    @SneakyThrows
    public ResultData<?> couponDestroy(CouponPaymetDto cw) {
        log.info("核销码：{}", cw.getCouponNo());
        String couponNo = cw.getCouponNo();
        String[] prefix = couponNo.split("_");
        couponNo = prefix[1];

            //去到核销码前缀
            cw.setCouponNo(couponNo);
            //获取券信息
            List<CouponUser> couponUsersInfo = couponService.selectUserAllCoupons(CouponUser.builder().couponNo(cw.getCouponNo()).build());
            log.info("获取优惠券信息：{}", couponUsersInfo);
            if (couponUsersInfo.isEmpty()) {
                return ResultData.error("没找到优惠券" + couponNo);
            }
            //获取核销人员信息
            SysUser sysUser = posMachineService.selectUserByUserId(cw.getOilPersonnelId());
            if(sysUser==null){
                return ResultData.error("没找到核销员工" + cw.getOilPersonnelId());
            }
            log.info("获取核销人员信息：{}", sysUser);
            //核销洗车券
            CouponUser couponUser = couponUsersInfo.get(0);
            //根据油站id获取油品信息
            List<Oil> listByStationId = staOilGunMapper.getListByStationId(Long.valueOf(cw.getStationId()));

            String enterpriseId = sysUser.getEnterpriseId();
            String couponUserEnterpriseId = couponUser.getEnterpriseId().toString();
            if (!enterpriseId.equals(couponUserEnterpriseId)) {
                return ResultData.error(CodeMsg.CAN_BE_HERE);
            }
            String couponStaNames = couponUser.getCouponStaNames();
            Station station = enterpriseService.selectStationById(Integer.valueOf(sysUser.getStationId()));
            String stationName = station.getStationName();
            List<String> nameList = Arrays.asList(couponStaNames.split(","));

            if (!nameList.contains(stationName)) {
                return ResultData.error(CodeMsg.CAN_BE_HERE);
            }
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (simpleDateFormat.parse(couponUsersInfo.get(0).getCouponEffectiveTime()).after(new Date())) {

                //状态
                if ("0".equals(couponUser.getCouponIsUsed())) {

                    CouponTemplate couponTemplateInfo = couponUser.getCouponTemplateInfo();

                    String effectiveTimeType = couponTemplateInfo.getEffectiveTimeType();
                    if (null != effectiveTimeType && effectiveTimeType.equals("1")) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String effectiveTimeEnd = sdf.format(couponTemplateInfo.getEffectiveTimeEnd());
                        String effectiveTimeStart = sdf.format(couponTemplateInfo.getEffectiveTimeStart());
                        if (simpleDateFormat.parse(effectiveTimeStart).after(new Date())) {
                            return ResultData.error(CodeMsg.TIME_IS_NOT_UP);
                        }

                    }

                    //判断是否洗车券及状态
                    if (ObjectUtils.isNotEmpty(couponTemplateInfo)  && "1".equals(couponTemplateInfo.getCouponTemplateStatus())) {
                        if (null == couponTemplateInfo.getVerification() || Arrays.asList(couponTemplateInfo.getVerification().split(",")).contains(sysUser.getStationId())) {
                            //更新用户优惠券信息
                            int i1 = this.updateCouponUser(CouponUser.builder().verificationType(2).couponNo(cw.getCouponNo()).verificationTime(new Date()).couponIsUsed("1").verificationUserAccount(sysUser.getUserName()).verificationUserPhone(sysUser.getPhonenumber()).build());
                            //更新优惠券使用模板数量
                            int i = this.updateCouponTemplate(CouponTemplate.builder().couponTemplateId(couponTemplateInfo.getCouponTemplateId()).useCouponNum(couponTemplateInfo.getUseCouponNum() + 1).build());
                            //记录在优惠券核销表
                            Integer i2 = addCancelCouponRecord(couponUser, cw);
                            if (i != 1 || i1 != 1 || i2 != 1) {
                                log.error("更新用户优惠券信息:{},更新优惠券使用模板数量:{},记录优惠券核销表:{}", i, i1, i2);
                                throw new CustomException("核销失败");
                            }
                            return ResultData.success("核销成功");
                        }
                    }
                }
                return ResultData.error(CodeMsg.CAR_WASH_TICKET_EXPIRED);
            }
            return ResultData.error(CodeMsg.TIME_IS_NOT_UP);

    }

    @Override
    public void batchPushWxGzhCouponExpire() {
        try{
            //查询所有油企对应的消费券推送规则
            List<CouponPushMessageRuleVo> couponPushMessageRuleVoList = couponMapper.selectCouponPushMessageRule();
            log.info("所有油企对应的消费券推送规则:{}", JSONObject.toJSONString(couponPushMessageRuleVoList));
            if(CollectionUtil.isNotEmpty(couponPushMessageRuleVoList)){
                for (CouponPushMessageRuleVo couponPushMessageRuleVo : couponPushMessageRuleVoList) {
                    String now = DateTimeFormatter.ofPattern("HH:mm").format(LocalTime.now());
                    log.info("当前时间:{}", now);
                    //判断当前油企推送开关和推送时间是否满足推送条件
                    if(CouponSwitchConstant.COUPON_SWITCH_NO.equals(couponPushMessageRuleVo.getCouponSwitch())){
                        //判断大于选择的时间小于夜晚8点执行
                        if(now.compareTo(couponPushMessageRuleVo.getPushTime())>=0 && now.compareTo("20:00")<=0){
                            CouponUserDto couponUserDto = new CouponUserDto();
                            couponUserDto.setEnterpriseId(couponPushMessageRuleVo.getEnterpriseId().intValue());
                            //判断当前油企推送规则
                            if(CouponPushRuleEnum.COUPON_PUSH_RULE_ENUM_1.getCode()==couponPushMessageRuleVo.getRule()){
                                couponUserDto.setIntervalDays(1L);
                            }else if(CouponPushRuleEnum.COUPON_PUSH_RULE_ENUM_2.getCode()==couponPushMessageRuleVo.getRule()){
                                couponUserDto.setIntervalDays(3L);
                            }else if(CouponPushRuleEnum.COUPON_PUSH_RULE_ENUM_3.getCode()==couponPushMessageRuleVo.getRule()){
                                couponUserDto.setIntervalDays(7L);
                            }
                            List<CouponUserVo> couponUserVos = couponMapper.selectUsefulExpireCoupon(couponUserDto);
                            log.info("用户所有即将到期的优惠券:{}", JSONObject.toJSONString(couponUserVos));
                            Enterprise enterprise = enterpriseService.selectEnterpriseInfo(couponPushMessageRuleVo.getEnterpriseId().intValue());
                            log.info("油企信息:{}", JSONObject.toJSONString(enterprise));
                            if(CollectionUtil.isNotEmpty(couponUserVos)){
                                for (CouponUserVo couponUserVo : couponUserVos) {
                                    AppUserInfo appUserInfo = new AppUserInfo();
                                    appUserInfo.setStationId(couponPushMessageRuleVo.getEnterpriseId().intValue());
                                    appUserInfo.setMobilePhone(couponUserVo.getMobilePhone());
                                    List<AppUserInfo> appUserInfoList = appUserInfoService.selectAppUserInfoByMobilePhoneAndStationId(appUserInfo);
                                    log.info("公众号用户信息:{}", JSONObject.toJSONString(appUserInfoList));
                                    if(CollectionUtil.isEmpty(appUserInfoList)){
                                        continue;
                                    }
                                    //判断是否改变了规则，如果改变了规则就判断上一次有没有推送过
                                    if(couponPushMessageRuleVo.getRule()==couponPushMessageRuleVo.getBeforeRule()){
                                        if(appUserInfoList.get(0).getPushTime()!=null && (appUserInfoList.get(0).getPushTime().plusDays(couponUserDto.getIntervalDays())).isAfter(LocalDateTime.now())){
                                            continue;
                                        }
                                    } else {
                                        //如果推送过就判断距离上次推送的时间过了多久
                                        if(appUserInfoList.get(0).getIsPush()!=null && appUserInfoList.get(0).getIsPush()==1){
                                            if(appUserInfoList.get(0).getPushTime()!=null && (appUserInfoList.get(0).getPushTime().plusDays(couponUserDto.getIntervalDays())).isAfter(LocalDateTime.now())){
                                                continue;
                                            }
                                        }
                                    }
                                    String  blogOpenid = appUserInfoList.get(0).getBlogOpenid();
                                    //优惠券失效公众号推送通知
                                    Map<String, String> templateDataMap = new HashMap<>();
                                    templateDataMap.put("openid", blogOpenid);
                                    templateDataMap.put("stationName", enterprise.getEnterpriseName());
                                    templateDataMap.put("couponContent", "您有" + couponUserVo.getCouponSum() + "张优惠券"+ couponUserDto.getIntervalDays() +"天内到期，请及时使用");
                                    wxPushUtil.sendTemplateMsg(couponPushMessageRuleVo.getEnterpriseId().intValue(), templateDataMap,WxTemplateEnum.COUPON_DISTRIBUTION);
                                    //更新推送时间和推送状态
                                    CompletableFuture.runAsync(()->{
                                        couponMapper.updateCouponPushTime(couponPushMessageRuleVo.getEnterpriseId().intValue(),couponUserVo.getMobilePhone());
                                    });
                                }
                            }
                        }
                    }
                }
            }
        }catch (RuntimeException e){
            log.error("优惠券到期提醒失败：{}",e.getMessage());
        }
    }

    private PayOrder setAddPayOrderParam(SysUser sysUser, CouponUser couponUser, carWashPaymentDto cw) throws Exception {
        Enterprise enterprise = enterpriseService.selectEnterpriseInfo(cw.getEnterpriseId());
        log.info("获取油企信息：{}",enterprise);
        if (ObjectUtils.isEmpty(enterprise)){
            throw new CustomException("查不到油企信息");
        }
        //获取用户信息
        List<AppUserInfo> appUserInfos = appUserInfoService.selectAppUserInfoByMobilePhoneAndStationId(
                AppUserInfo.builder()
                        .mobilePhone(couponUser.getMobilePhone()).
                        stationId(enterprise.getEnterpriseId())
                        .build());
        log.info("获取用户信息：{}",appUserInfos);
        if (appUserInfos.isEmpty()){
            throw new CustomException("找不到该用户信息");
        }
        AppUserInfo appUserInfo = appUserInfos.get(0);
        PayOrder newPayOrder = new PayOrder();
        String orderNo= com.platform.qujia.utils.StringUtils.generateOrdNo();
        newPayOrder.setConsumer(appUserInfo.getBlogNickName());     //用户名称
        newPayOrder.setConsumerId(appUserInfo.getUserId());     //用户id
        newPayOrder.setEnterpriseId(cw.getEnterpriseId());  //油企id
        newPayOrder.setEnterpriseName(enterprise.getEnterpriseName());      //油企名称
        newPayOrder.setAppType(cw.getAppType());            //订单来源容器
        newPayOrder.setPayType(cw.getPayType());            //支付类型
        newPayOrder.setOrderOriginType(cw.getOrderOriginType());    //订单来源
        newPayOrder.setStationName(cw.getStationName());    //油站名称
        newPayOrder.setCustomerPhone(couponUser.getMobilePhone());          //用户手机号
//        newPayOrder.setDiscountCouponAmt(CarWashEnum.AMOUNT.getValue());  //优惠券金额
        newPayOrder.setDiscountCoupon(String.valueOf(couponUser.getCouponUserId()));    //用户优惠券id
        newPayOrder.setOrderNo(orderNo);                                          //订单号
        newPayOrder.setStationId(cw.getStationId());                  //油站id
        newPayOrder.setStatus("1");                                                //创建订单 未支付状态 0
        newPayOrder.setCreatedDate(new Timestamp(new Date().getTime()));           //创建时间
        newPayOrder.setOilGun(cw.getOilGun());                        //油枪号
        newPayOrder.setReceivableAmt(CarWashEnum.AMOUNT.getValue());      //订单应收金额
        newPayOrder.setOrderType(cw.getOrderType());    // 油品类
        newPayOrder.setOilName(cw.getOilName());        // 油品id
        newPayOrder.setAmt(CarWashEnum.AMOUNT.getValue());    //实收金额
        newPayOrder.setDiscountAmt(CarWashEnum.AMOUNT.getValue());          //优惠金额
        newPayOrder.setOilPersonnelId(sysUser.getUserId());             //加油员id
        newPayOrder.setPayDate(new Timestamp(new Date().getTime()));
        newPayOrder.setDiscountCouponAmt(couponUser.getCouponTemplateInfo().getCouponAmt().doubleValue());//优惠券金额
        //现金支付的状态（0申请1取消）
        newPayOrder.setXJStatus("1");
        newPayOrder.setUtmSource("1");
        newPayOrder.setOrderLiters("0");
        newPayOrder.setOilPirce(String.valueOf(couponUser.getCouponTemplateInfo().getCouponAmt()));
//        //费率
//        Map<String,Object> map=getServiceChargew(addCarWashOrderDto.getStationId(),null);
//        BigDecimal serviceCharge=map.get("serviceCharge")==null?BigDecimal.ZERO:new BigDecimal(map.get("serviceCharge").toString());
//        newPayOrder.setServiceCharge(serviceCharge);
//        //渠道手续费支付方 0司机/1油企 channelFeePayer
//        newPayOrder.setChannelFeePayer("1");
//        //渠道费
//        newPayOrder.setCommission(Double.valueOf("0.00"));
        return newPayOrder;
    }

    //优惠券核销记录表
    private Integer addCancelCouponRecord(CouponUser couponUser, newCarWashPaymetDto ccd) {

        CouponWriteOffRecords couponWriteOffRecords = new CouponWriteOffRecords();
        couponWriteOffRecords.setCouponNo(couponUser.getCouponNo());
        couponWriteOffRecords.setAmt(couponUser.getCouponTemplateInfo().getCouponAmt());
        couponWriteOffRecords.setCreatedDate(new Date());
        couponWriteOffRecords.setEnterpriseId(Long.valueOf(couponUser.getEnterpriseId()));
        couponWriteOffRecords.setStationId(Long.valueOf(ccd.getStationId()));
        couponWriteOffRecords.setCouponType(Integer.valueOf(couponUser.getCouponTemplateInfo().getCouponType()));
        couponWriteOffRecords.setWriteOffPersonnelId(Integer.valueOf(ccd.getOilPersonnelId()));
        return couponWriteOffRecordsMapper.insert(couponWriteOffRecords);
    }
    //优惠券核销记录表
    private Integer addCancelCouponRecord(CouponUser couponUser, CouponPaymetDto ccd) {

        CouponWriteOffRecords couponWriteOffRecords = new CouponWriteOffRecords();
        couponWriteOffRecords.setCouponNo(couponUser.getCouponNo());
        couponWriteOffRecords.setAmt(couponUser.getCouponTemplateInfo().getCouponAmt());
        couponWriteOffRecords.setCreatedDate(new Date());
        couponWriteOffRecords.setEnterpriseId(Long.valueOf(couponUser.getEnterpriseId()));
        couponWriteOffRecords.setStationId(Long.valueOf(ccd.getStationId()));
        couponWriteOffRecords.setCouponType(Integer.valueOf(couponUser.getCouponTemplateInfo().getCouponType()));
        if(ccd.getOilPersonnelId()!=null){
            couponWriteOffRecords.setWriteOffPersonnelId(Integer.valueOf(ccd.getOilPersonnelId()));
        }
        return couponWriteOffRecordsMapper.insert(couponWriteOffRecords);
    }

    @Override
    public void saveBatchCouponUseDetails(List<CouponUser> couponUsersList) {
        couponMapper.saveBatchCouponUseDetails(couponUsersList);
    }

    @Override
    public void deleteCouponUseDetailByOrderNo(String orderNo) {
        couponMapper.deleteCouponUseDetailByOrderNo(orderNo);
    }
}
